﻿using System;
using System.Text;
using System.IO;

namespace Pretext {
    public class FileProcessor {

        public event EventHandler<FileEventArgs> FileSaved;

        public string SourceFile { get; private set; }
        public string DestinationFile { get; private set; }

		bool somethingWentWrong = false;

        public FileProcessor(string file) {

            SourceFile = file;
            DestinationFile = Path.GetDirectoryName(file) + @"\" + Path.GetFileNameWithoutExtension(file);

        }

        public void Process() {

			BindLogItemEvent();

            // load the source file
            string source = null;
            try {
                source = File.ReadAllText(SourceFile);
            } catch (Exception ex) {
				Pretexter.Session.LogException(ex, null);
            }

			if (somethingWentWrong) {
				UnbindLogitem();
				return;
			}

            // process the string
			string output = Pretexter.ProcessString(source, SourceFile);

			if (somethingWentWrong) {
				UnbindLogitem();
				return;
			}

            try {
                
                // TODO: write multiple files if there are multiple outputs

                // write the destination file
                File.WriteAllText(DestinationFile, output);

                if (FileSaved != null)
                    FileSaved(this, new FileEventArgs(DestinationFile));

            } catch (Exception ex) {
				Pretexter.Session.LogException(ex, null);
            }

			UnbindLogitem();

        }

		void BindLogItemEvent() {
			Pretexter.Session.LogItem += new EventHandler<Pretext.Logging.LogEventArgs>(Session_LogItem);
		}
		void UnbindLogitem() {
			Pretexter.Session.LogItem -= new EventHandler<Pretext.Logging.LogEventArgs>(Session_LogItem);
		}

		void Session_LogItem(object sender, Pretext.Logging.LogEventArgs e) {

			if (e.LogItem.Type == Pretext.Logging.LogItemType.Error) {
				somethingWentWrong = true;
			}

		}

    }
}